import { AppRouteRecordRaw } from '@fssc/admin';
import { Router, RouteRecordRaw, RouteComponent } from 'vue-router';
import { usePermissionStoreWithOut, useUserStoreWithOut } from '../store/index.js';
import { Layout, staticRoutes } from './static-routes';
import Cookie from 'js-cookie';
import { TOKEN_KEY, FsscAppUtil } from '../util/index'

export {
  Layout,
  staticRoutes
}

export type InitRouterOption = {
  layoutComponent: RouteComponent,
  router: Router,
  routes: RouteRecordRaw[],
  fsscAppUtil: FsscAppUtil,
  staticRoutes?: RouteRecordRaw[],
  whiteList?: string[],
}

// 初始化路由拦截
export function initRouter(option: InitRouterOption){
  const router = option.router;
  const fsscAppUtil = option.fsscAppUtil;
  const env = fsscAppUtil.option.env;
  const initRoutes = option.staticRoutes || staticRoutes

  initRoutes.forEach((route) => {
    if (option.layoutComponent && route.component === Layout) {
      route.component = option.layoutComponent;
    }
    router.addRoute(route as unknown as RouteRecordRaw);
  })

  const whiteList = option.whiteList || [''];

  router.beforeEach(async (to, from) => {
    let token = Cookie.get(TOKEN_KEY);
    if (!token) {
      if (whiteList && whiteList.indexOf(to.path) !== -1) {
        return true
      } else if (fsscAppUtil.isPassportLogin()){
        const userStore = useUserStoreWithOut();
        userStore.requestLogout(false)
        return false;
      } else if (to.path == '/login') {
        return true;
      } else  {
        return { path: `/login?redirect=${to.path}`}
      }
    }

    const permissionStore = usePermissionStoreWithOut();
    if (!permissionStore.getIsAddRouters) {
      const userStore = useUserStoreWithOut();
      let userInfo = userStore.getUserInfo;
      if (!userInfo) {
        await userStore.requestUserInfo();
        userInfo = userStore.getUserInfo;
      }
      permissionStore.generateRoutes(option.routes as unknown as AppRouteRecordRaw[], userInfo.menuCodeList || []);
      if(permissionStore.getAddRouters.length > 0){
        router.addRoute({ path: '/', name: 'Root', redirect: { name: permissionStore.getAddRouters[0].name } });
      }

      permissionStore.getAddRouters.forEach((route) => {
        router.addRoute(route as unknown as RouteRecordRaw);
      });

      permissionStore.setIsAddRouters(true);
      const redirectPath = from.query.redirect || to.path;
      const redirect = decodeURIComponent(redirectPath as string);
      const nextData = to.path === redirect ? { ...to, replace: true } : router.resolve(redirect);
      return nextData
    } else {
      if (to.path === '/login') {
        return { path: '/' };
      } else {
        return true
      }
    }
  });

  router.onError(async (err) => {
    await fsscAppUtil.checkMessageToRefresh(err)
  })
}
